<template>
  <div :style="`margin:${isAdmin ? 0 : -15}px`">
    <ZgDialog title="提交流程" v-model="showSubmit" @ok="onSubmitOk">
      <Submit :selectedNextUser="selectedNextUser" :formInfo="formInfo"></Submit>
    </ZgDialog>
    <ZgDialog title="退回流程" width="60%" v-model="showReturn" @ok="onReturnOk">
      <Return
        :flowInfo="flowInfo"
        :newDate="new Date()"
        ref="Return"
        @returnList="returnList"
        @backDescsChange="backDescsChange"
      ></Return>
    </ZgDialog>
    <ZgDialog title="作废流程" width="60%" v-model="showCancel" @ok="onCancelOk">
      <Cancel ref="cancel"></Cancel>
    </ZgDialog>
    <ZgDrawer width="30%" v-model="showFlowInst">
      <div class="wfull scroll pt15" :style="{ height: `${winHeight - 90}px` }">
        <a-timeline>
          <a-timeline-item v-for="item in stepInfoList" :key="item.id" :color="item.color">
            <div class="mb10">{{ item.stepName }}</div>
            <div>
              <a-tag
                :color="item.color"
              >{{ item.userName
              }}{{
                item.stepInstState == '1'
                  ? '【进行中】'
                  : item.stepInstState == '2'
                    ? '【已完成】'
                    : item.stepInstState == '4'
                      ? '【已退回】'
                      : ''
              }}{{ item.successTime }}</a-tag
              >
            </div>
          </a-timeline-item>
        </a-timeline>
      </div>
    </ZgDrawer>
    <div class="pl15 pr15 pt10">
      <a-row>
        <a-col :span="12">
          <div class="fw8 fs14">
            {{ formInfo.autoflow && formInfo.autoflow.flowName ? formInfo.autoflow.flowName : '' }}/
            {{ formInfo.autoflowStep && formInfo.autoflowStep.stepName ? formInfo.autoflowStep.stepName : '' }}
          </div>
        </a-col>
        <a-col :span="12" class="tar flx-e">
          <a-button v-if="!isAdmin" class="mr10" type="link" @click="toClose">
            <i class="fa fa-power-off mr5" />关闭窗口
          </a-button>
        </a-col>
      </a-row>
    </div>
    <div class="pd10">
      <div style="background: #f6f6f6; padding: 10px">
        <a-row :gutter="10">
          <a-col :span="isAdmin ? 16 : 14">
            <div class="flx-s">
              <div class="mr10">下一环节：</div>
              <ZgSelect
                :modelVal="selectedNextStep"
                :options="formInfo.nextStepList"
                :width="200"
                class="mr25"
                @change="onNextStepChange"
              ></ZgSelect>
              <div class="mr10">处理人：</div>
              <!-- <a-input class="w100 mr10" disabled="" value="某某某"></a-input> -->
              <ZgInput placeholder="下一环节处理人" :width="200" v-model="selectedNextUser.name" :disabled="true" />
              <ZgButton @click="openUserDialog">选择处理人</ZgButton>
              <!--<ZgUserSelect icon="user" title="选择处理人"></ZgUserSelect>-->
              <ZgPersonnelSearch
                @onOk="selectNextuser"
                :isSingle="false"
                ref="ZgPersonnelSearch"
                dialogTitle="选择环节处理人"
                :searchForm="{ userIds: formInfo.nextUserList }"
              ></ZgPersonnelSearch>
            </div>
          </a-col>
          <a-col :span="isAdmin ? 8 : 10" class="flx-e">
            <ZgCheckbox v-model="showFlowData" class="mr10" @change="flowDataInfo">查看流程单据</ZgCheckbox>
            <ZgDropdown v-if="isAdmin">流程操作</ZgDropdown>
            <div v-else class="flx-s">
              <ZgButton icon="check-circle" type="primary" @click="handSeal" class="mr10">手动盖章</ZgButton>
              <ZgButton icon="check-circle" type="primary" @click="onSubmitOk" class="mr10">提交</ZgButton>
              <ZgButton icon="arrow-circle-left" type="default" @click="toReturn" class="mr10">退回</ZgButton>
              <ZgButton icon="eraser" type="default" class="mr10" @click="toCancel">作废</ZgButton>
              <ZgButton icon="eye" type="default" @click="getAllStepInstanceByStepInstCode">跟踪</ZgButton>
            </div>
          </a-col>
        </a-row>
        <a-row class="mt10" v-if="showFlowData">
          <a-col :span="24">
            <a-collapse v-model="activeKey" accordion>
              <a-collapse-panel key="1" header="主流程单据">
                <div class="flx-s" style="flex-wrap: wrap">
                  <div class="file flx-s" v-for="item in matchedMainPdfList" :key="item.id">
                    <a class="mr15">{{ item.pdfFileName }}</a>
                    <i class="fa fa-download mr8 cpt" @click="downLoadPDF(item)"></i>
                    <i class="fa fa-search cpt" @click="showPDF(item)"></i>
                  </div>
                </div>
              </a-collapse-panel>
              <a-collapse-panel key="2" header="个性化单据">
                <div class="flx-s" style="flex-wrap: wrap">
                  <div class="file flx-s" v-for="item in matchedCustomPdfList" :key="item.id">
                    <a class="mr15">{{ item.pdfFileName }}</a>
                    <i class="fa fa-download mr8 cpt" @click="downLoadPDF(item)"></i>
                    <i class="fa fa-search cpt" style="" @click="showPDF(item)"></i>
                  </div>
                </div>
              </a-collapse-panel>
              <a-collapse-panel key="3" header="关联流程单据">
                <div class="flx-s pt20 pl10 pos-rlt" style="flex-wrap: wrap; border: dashed 1px #ccc">
                  <div class="pos-abs bg-white pd5" style="top: -18px; left: 20px; color: #3fa4db">
                    流程实例编号：xxxxxxxxxxxxxxxxxx
                  </div>
                  <div class="file flx-s" v-for="i in 10" :key="`master${i}`">
                    <a class="mr15">某某文件.xlsx</a>
                    <i class="fa fa-download mr8 cpt"></i>
                    <i class="fa fa-search cpt"></i>
                  </div>
                </div>
              </a-collapse-panel>
            </a-collapse>
          </a-col>
        </a-row>
      </div>
    </div>
    <a-row>
      <a-col :span="24">
        <Form ref="forms" :formInfo="formInfo" @save="onFormSave" @createPdf="createPdf"></Form>
      </a-col>
    </a-row>
    <Zgseal ref="seal"></Zgseal>
  </div>
</template>

<script>
import { pageMixin } from '@/core/page-mixin'

import Form from './Form'
import Submit from './Submit'
import Return from './Return'
import Cancel from './Cancel'
export default {
  mixins: [pageMixin],
  props: {
    flowInfo: {
      type: Object,
      default: () => ({})
    },
    isAdmin: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Form,
    Submit,
    Return,
    Cancel
  },
  data () {
    return {
      left: 5,
      right: 5,
      current: 0,
      tab: 1,
      activeKey: ['1'],
      showSubmit: false,
      showReturn: false,
      showFlowInst: false,
      showFlowData: false,
      showCancel: false,
      formInfo: {},
      selectReturnList: [],
      backDescs: '',
      pdfUrl: '',
      selectedNextStep: null,
      stepInfoList: [],
      selectedNextUser: {
        name: '',
        id: ''
      },
      matchedMainPdfList: [],
      matchedCustomPdfList: []
    }
  },
  watch: {
    flowInfo: {
      handler (newVal) {
        console.log(newVal, 'flow')
        if (newVal && newVal.instCode && newVal.stepInstCode) {
          this.getStepData()
          this.selectedNextUser = {
            id: '',
            name: ''
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    // 重置表单数据
    this.$nextTick(() => {
      if (this.$refs.form) {
        this.$refs.form.resetForm()
      }
    })
    const dataBtns = [
      { name: '查看流程单据', code: 'lookProcess' },
      { name: '手动盖章', code: 'handSeal' },
      { name: '提交', code: 'submit' },
      { name: '作废', code: 'viodProcess' },
      { name: '退回', code: 'returnProcess' },
      { name: '跟踪', code: '' },
      { name: '选择数据', code: '' },
      { name: '保存草稿', code: 'saveDraft' },
      { name: '保存单据', code: 'saveDocument' },
      { name: '关闭', code: 'close' }

    ]
    // 填充场景数据
    this.SET_CONTEXT({
      flag: this.pageCode,
      // 数据列表
      dataList: [],
      // 筛选条件
      condition: [],
      // 按钮操作
      operate: this.operatesArr({ dataBtns: dataBtns }),
      // 视图字段
      form: []
    })
    // this.operatesArr(dataBtns)
  },
  methods: {
    getStepData () {
      this.$http.post('/zg-autoflow/flow/workflowManage/getStepData', this.flowInfo, (res) => {
        this.formInfo = res
        const obj = {
          stepCode: res.autoflowStep.stepCode,
          instCode: this.flowInfo.instCode
        }
        this.$http.post('/zg-autoflow/flow/settleWorkflowStep/getNextStepConfig', obj, (res) => {
          console.log(res, 'res0')
          this.selectedNextStep = ''
          this.formInfo.nextStepList = res.map((item) => ({
            label: item.stepName,
            value: item.stepCode
          }))
          this.$nextTick(() => {
            this.selectedNextStep = res[0].stepCode
          })
          console.log(this.formInfo.nextStepList, 'this.formInfo.nextStepList')
        })
        this.$http.post('/zg-autoflow/flow/settleWorkflowStepUser/getNextStepUserList', obj, (res) => {
          this.formInfo.nextUserList = res
        })
      })
    },
    returnList (val) {
      this.selectReturnList = val
    },
    showPDF (item) {
      window.open(process.env.VUE_APP_MINIO_PROXY + item.pdfFilePath)
    },
    downLoadPDF (item) {
      // 你可以根据实际类型传递
      const type = 'application/pdf' // 或根据item类型动态设置
      this.$http.downloadMinio(process.env.VUE_APP_MINIO_PROXY + item.pdfFilePath, item.pdfFileName, type)
    },
    flowDataInfo (val) {
      console.log(val)
      if (val) {
        this.getFlowInfo()
      }
    },
    async getFlowInfo () {
      // 用Promise包装原有接口请求
      const getMainPdfList = () =>
        new Promise((resolve) => {
          this.$http.post(
            '/zg-autoflow/flow/settleWorkflowInstance/getMainPdfList',
            { instCode: this.flowInfo.instCode, stepInstCode: this.flowInfo.stepInstCode },
            (res) => resolve(res)
          )
        })

      const getExtStepConfig = () =>
        new Promise((resolve) => {
          this.$http.post(
            '/zg-autoflow/autoflow/ext/step/config',
            { flowCode: this.formInfo.autoflowStep.flowCode, stepNo: this.formInfo.autoflowStep.stepCode },
            (res) => resolve(res.extStepConfig)
          )
        })

      // 并发请求
      const [mainPdfList, extStepConfig] = await Promise.all([getMainPdfList(), getExtStepConfig()])
      const ownIds = (extStepConfig.ownFlowForms || '').split(',')
      this.matchedMainPdfList = mainPdfList.filter((item) => item.isMain === '1' && ownIds.includes(item.formId))
      this.matchedCustomPdfList = mainPdfList.filter((item) => item.isMain !== '1' && ownIds.includes(item.formId))
    },
    getAllStepInstanceByStepInstCode () {
      this.$http.post(
        '/zg-autoflow/workflowManage/getAllStepInstanceByStepInstCode',
        { instCode: this.flowInfo.instCode },
        (res) => {
          this.showFlowInst = true
          this.stepInfoList = res.map((item) => ({
            ...item,
            color:
              item.stepInstState === '1'
                ? 'blue'
                : item.stepInstState === '2'
                ? 'green'
                : ['3', '4', '9'].includes(item.stepInstState)
                ? 'red'
                : 'gray'
          }))
        }
      )
    },
    toClose () {
      this.showSubmit = false
      this.$emit('close')
    },
    toggleLeft () {
      this.left = this.left === 5 ? 0 : 5
    },
    toggleRight () {
      this.right = this.right === 5 ? 0 : 5
    },
    toSubmit () {
      // 判断 bizFormDetail 是否为数组
      console.log(this.formInfo.bizFormDetail, 'this.formInfo.bizFormDetail')
      if (Array.isArray(this.formInfo.bizFormDetail)) {
        // 检查是否有任何一个 state 不等于 2
        const hasNotSaved = this.formInfo.bizFormDetail.some((item) => item.state !== 2)
        if (hasNotSaved) {
          this.$message.warning('请先保存')
          return
        }
      }
      if (this.selectedNextStep === '') {
        this.$message.warning('请选择下一环节')
        return
      }
      if (this.selectedNextUser.id === '') {
        this.$message.warning('请选择下一环节处理人')
        return
      }
      this.showSubmit = true
    },
    async handSeal () {
      const url = encodeURI(this.pdfUrl)
      try {
        const response = await fetch(url, {
          method: 'GET'
        })
        if (!response.ok) throw new Error('网络原因请求失败！')

        const arrayBuffer = await response.arrayBuffer()
        const blob = new Blob([arrayBuffer], { type: 'application/pdf;charset=UTF-8' })
        const file = new File([blob], 'malan-' + this.randomString(12) + '.pdf', { type: blob.type })
        const formData = new FormData()
        formData.append('files', file)
        this.$http.capost('/v2/api/serCebSign/uploadBatchFile', formData, (res) => {
          const fileflag = res[0].fileflag
          this.$refs.seal.openSeal(fileflag)
        })
        // 这里 file 就是你要的 File 对象，可以后续处理
        // 例如：console.log(file)
      } catch (e) {
        alert('网络原因请求失败！')
      }
    },

    onSubmitOk () {
      const obj = {
        ...this.flowInfo,
        nextStepCode: this.selectedNextStep,
        nextUserId: this.selectedNextUser.id
      }
      this.$http.post('/zg-autoflow/flow/workflowManage/submitWorkflow', obj, (res) => {
        this.$message.success('提交成功')

        this.toClose()
      })
    },
    toReturn () {
      this.showReturn = true
      this.$nextTick(() => {
        this.$refs.Return.initData()
      })
    },
    toCancel () {
      this.showCancel = true
      this.$refs.textArea = ''
    },
    onCancelOk () {
      this.$refs.cancel.submit(this.flowInfo.instCode, () => {
        this.showCancel = false
        this.toClose()
      })
    },
    onReturnOk () {
      if (this.backDescs === '') {
        this.$message.warning('退回原因不能为空')
        return
      }
      const obj = {
        backDescs: this.backDescs,
        backStepInstCodes: this.selectReturnList[0].stepInstCode,
        curInstCode: this.selectReturnList[0].instCode,
        curStepInstCode: this.flowInfo.stepInstCode
      }
      this.$http.post('/zg-autoflow/flow/workflowManage/backWorkflow', obj, (res) => {
        this.showReturn = false
        this.toClose()
      })
    },
    backDescsChange (val) {
      this.backDescs = val
    },
    onFormSave (obj) {
      // 如果 bizFormDetail 是数组，则循环查找并替换
      if (Array.isArray(this.formInfo.bizFormDetail)) {
        console.log('走了')
        const index = this.formInfo.bizFormDetail.findIndex((item) => item.id === obj.id)
        if (index !== -1) {
          console.log(index, '走了1')
          // 找到匹配的项，替换它
          this.$set(this.formInfo.bizFormDetail, index, obj)
        }
      }
    },
    onNextStepChange (value) {
      this.selectedNextStep = value
    },
    selectNextuser (data) {
      this.selectedNextUser.id = data.map((item) => item.id).join(',')
      this.selectedNextUser.name = data.map((item) => item.name).join(',')
    },
    openUserDialog () {
      this.$refs.ZgPersonnelSearch.open()
    },
    // 生成文件
    createPdf (obj, url) {
      this.pdfUrl = url
    }
  }
}
</script>

<style scoped>
.file {
  border: solid 1px #ddd;
  border-radius: 4px;
  background: #f2f2f2;
  color: #3fa4db;
  padding: 4px 10px;
  margin-right: 15px;
  margin-bottom: 10px;
}
</style>
